package com.jin.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jin.bean.User;
import com.jin.dao.MaterialMapper;
import com.jin.dao.UnitMapper;
import com.jin.dao.UserMapper;
import com.jin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private MaterialMapper materialMapper;

    @Override
    public boolean checkUserExists(String username) {
        return lambdaQuery().eq(User::getUsername, username).count() > 0;
    }


    @Override
    public boolean login(String username, String password) {
        System.out.println("login");
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);

        User user = userMapper.findByUsername(username);
        System.out.println("User: " + user);

        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            System.out.println("Login successful.");
            return true;
        } else {
            System.out.println("Login failed.");
            return false;
        }
    }

    @Override
    public User getUserByUsername(String username) {
        System.out.println("getUserByUsername");
        System.out.println("Username: " + username);

        User user = userMapper.findByUsername(username);
        System.out.println("User: " + user);

        return user;
    }

    @Override
    public boolean addUser(User user) {
        // 添加存在性检查
        if (checkUserExists(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        //  对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRegisterTime(new Date()); // 设置注册时间为当前时间
        return save(user);
    }

    @Override
    public boolean updateUser(User user) {
        // 获取原用户信息
        User originalUser = getById(user.getId());
        if (originalUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 如果修改了用户名
        if (!originalUser.getUsername().equals(user.getUsername())) {
            if (checkUserExists(user.getUsername())) {
                throw new RuntimeException("新用户名已被占用");
            }
        }

        // 处理密码字段（为空时不更新）
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(originalUser.getPassword());
        } else {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        return updateById(user);
    }

    @Override
    public boolean deleteUser(Integer id) {
        int result = userMapper.deleteUser(id);
        return result > 0;
    }

    @Override
    public boolean resetPassword(String username, String newPassword) {
        System.out.println("resetPassword");
        System.out.println("Username: " + username);

        System.out.println("New Password: " + newPassword);

        User user = userMapper.findByUsername(username);
        if (user == null) {
            System.out.println("User does not exist.");
            return false;
        }


        String encodedNewPassword = passwordEncoder.encode(newPassword);
        user.setPassword(encodedNewPassword);
        int result = userMapper.updateById(user);
        if (result > 0) {
            System.out.println("Password updated successfully.");
            return true;
        } else {
            System.out.println("Failed to update password.");
            return false;
        }
    }

}
